<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限列表</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <el-row
              :class="['bdbottom', index === 0 ? 'bdtop' : '', 'cventer']"
              :key="item.id"
              v-for="(item, index) in row.children"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag type="" closable @close="removeRightById(row, item.id)">
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级 -->
                <el-row
                  :class="[index1 === 0 ? '' : 'bdtop', 'cventer']"
                  :key="item1.id"
                  v-for="(item1, index1) in item.children"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      :key="item2.id"
                      v-for="item2 in item1.children"
                      type="warning"
                      closable
                      @close="removeRightById(row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              tnpe="warning"
              icon="el-icon-setting"
              @click="showSetRightDualog(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      // 控制分配权限对话框的显示和隐藏
      setRightDialogVisible: false,
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defkeys: []
    }
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      console.log(res)
      this.rolesList = res.data
      this.$message.success('获取角色列表成功')
    },
    // 根据id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示是否删除
      const confirm = await this.$confirm(
        '此操作会永远删除改权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirm !== 'confirm') {
        return this.$message.info('取消了删除操作')
      }
      // 发起用户请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      role.children = res.data
      this.$message.success('删除权限成功')
    },
    // 显示分配权限对话框
    async showSetRightDualog(scope) {
      this.roleId = scope.id
      // 展示分配权限对话框
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分配权限数据失败')
      }
      // 获取到的权限数据保存到data中
      this.rightsList = res.data
      // 递归获取三级节点的id
      this.getLeafKeys(scope, this.defkeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式获取角色下所有三级权限的id, 把它赋值到 defkeys 数组中
    getLeafKeys(node, arr1) {
      // 如果当前node节点不包含children 说明它是三级节点 把它push进arr数据
      if (!node.children) {
        return arr1.push(node.id)
      }
      // 不是三级节点 循环node.children
      node.children.forEach(item => {
        this.getLeafKeys(item, arr1)
      })
    },
    // 监听对话框权限的分配事件
    setRightDialogClosed() {
      this.defkeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treRef.getCheckedKeys(),
        ...this.$refs.treRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      // 发起用户请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配用户权限失败')
      }
      this.getRolesList()
      this.$message.success('分配用户权限成功')
      this.setRightDialogVisible = false
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.cventer {
  display: flex;
  align-items: center;
}
</style>
